package com.pingao.mp.modular.sys.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pingao.mp.config.dict.DictConfig;
import com.pingao.mp.modular.sys.entity.Role;
import com.pingao.mp.modular.sys.entity.User;
import com.pingao.mp.modular.sys.service.RoleService;
import com.pingao.mp.modular.sys.service.UserService;
import com.pingao.mp.utils.Md5;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 闻品高
 * @since 2018-09-26
 */
@Controller
@RequestMapping("/sys/user")
public class UserController {

    private final static Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DictConfig dictConfig;

    @GetMapping("/login")
    public Object login() {
        return "sys/user/login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, Integer rememberMe) {
        return userService.login(username, password, rememberMe);
    }

    @GetMapping("/logout")
    @ResponseBody
    @RequiresUser
    public Object logout() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        Map<String, Object> map = new HashMap<>();
        map.put("status", true);
        map.put("msg", "logout success");
        return map;
    }

    @GetMapping("/index")
    @RequiresPermissions("sys.user.index")
    public String index(ModelMap map) {
        map.addAttribute("roles", JSON.toJSONString(roleService.list(new QueryWrapper<Role>().select("id", "name"))));
        return "sys/user/index";
    }

    @GetMapping("/list")
    @ResponseBody
    @RequiresPermissions("sys.user.index")
    public Object list(@RequestParam("pageNumber") Integer pageNumber,
                       @RequestParam("pageSize") Integer pageSize,
                       @RequestParam(value = "searchText", required = false) String searchText,
                       @RequestParam("sortName") String sortName,
                       @RequestParam("sortOrder") String sortOrder,
                       @RequestParam(value = "roleId", required = false) Integer roleId) {
        return userService.getUserList(pageNumber, pageSize, searchText, sortName, sortOrder, roleId);
    }

    @GetMapping("/add")
    @RequiresPermissions("sys.user.add")
    public String add(ModelMap map) {
        map.addAttribute("genders", dictConfig.getGenders());
        map.addAttribute("roles", roleService.list(new QueryWrapper<Role>().select("id", "name")));
        return "sys/user/add";
    }

    @PostMapping("/add")
    @RequiresPermissions("sys.user.add")
    @ResponseBody
    public Object add(User user) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", false);
        map.put("msg", "添加失败");
        user.setPassword(Md5.md5(user.getPassword()));
        boolean b = userService.save(user);
        if (b) {
            map.put("status", true);
            map.put("msg", "添加成功");
        }
        map.put("user", user);
        return map;
    }

    @GetMapping("/userExist")
    @RequiresPermissions("sys.user.add")
    @ResponseBody
    public Object userExist(@RequestParam(value = "name") String name) {
        Map<String, Object> map = new HashMap<>();
        Integer total = userService.count(new QueryWrapper<User>().eq("name", name).isNull("delete_time"));
        if (total > 0) {
            map.put("valid", false);
        } else {
            map.put("valid", true);
        }
        return map;
    }

    @GetMapping("/emailExist")
    @RequiresPermissions("sys.user.add")
    @ResponseBody
    public Object emailExist(@RequestParam(value = "email") String email) {
        Map<String, Object> map = new HashMap<>();
        Integer total = userService.count(new QueryWrapper<User>().eq("email", email).isNull("delete_time"));

        if (total > 0) {
            map.put("valid", false);
        } else {
            map.put("valid", true);
        }

        return map;
    }

    @PostMapping("/delete")
    @RequiresPermissions("sys.user.delete")
    @ResponseBody
    public Object delete(
            @RequestParam(value = "ids[]") List<Long> ids
    ) {
        Map<String, Object> map = new HashMap<>();
        for (Long id : ids) {
            if (id.equals(1L)) {
                continue;
            }
            User u = userService.getById(id);
            if (u != null) {
                u.setDeleteTime(LocalDateTime.now());
                u.updateById();
            }
        }
        map.put("status", true);
        map.put("msg", "删除成功");
        map.put("ids", ids);
        return map;
    }


    @GetMapping("/edit/{id}")
    @RequiresPermissions("sys.user.edit")
    public String edit(@PathVariable("id") Long id, ModelMap map) {
        User user = userService.getById(id);
        if (user == null) {
            throw new NullPointerException("该用户不存在或已被删除--this user is not exits,id=" + id);
        }
        map.addAttribute("genders", dictConfig.getGenders());
        map.addAttribute("roles", roleService.list(new QueryWrapper<Role>().select("id", "name")));
        map.addAttribute("user", user);
        return "sys/user/edit";
    }

    @PostMapping("/edit")
    @ResponseBody
    @RequiresPermissions("sys.user.edit")
    public Object edit(User user) {
        Map<String, Object> map = new HashMap<>();
        user.setUpdateTime(LocalDateTime.now());
        if (!user.getPassword().equals("")) {
            user.setPassword(Md5.md5(user.getPassword()));
        } else {
            user.setPassword(null);
        }
        if (!userService.updateById(user)) {
            map.put("status", false);
            map.put("msg", "保存用户出错......");
            return map;
        }
        map.put("status", true);
        map.put("msg", "保存用户成功");
        map.put("user", user);
        return map;
    }

    @GetMapping("/myInfo")
    @RequiresUser
    public String myInfo(ModelMap map) throws Exception {
        User sessionUser = userService.getSessionUser();
        Long id = sessionUser != null ? sessionUser.getId() : null;
        if (id == null || id < 1) {
            throw new Exception("登录用户不存在");
        }
        User user = userService.getById(id);
        if (user == null) {
            throw new Exception("登录用户不存在");
        }
        map.addAttribute("genders", dictConfig.getGenders());
        user.setRoleName(sessionUser.getRoleName());
        map.addAttribute("user", user);
        return "sys/user/myInfo";
    }

    @PostMapping("/myInfo")
    @ResponseBody
    @RequiresUser
    public Object myInfo(User user) {
        return userService.myInfo(user);
    }
}